package com.qingzhou.gateway.filter;

import com.qingzhou.common.core.web.api.ApiCode;
import com.qingzhou.common.core.web.api.ApiCodes;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.auth.AuthException;
import org.noear.solon.auth.AuthStatus;
import org.noear.solon.cloud.CloudClient;
import org.noear.solon.cloud.model.BreakerException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;

/**
 * 全局过滤器（包含限流、全局异常）
 * @author xm
 */
@Slf4j
@Component
public class GlobalFilter implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            // 如果注掉 pom中的 sentinel-solon-cloud-plugin依赖，CloudClient.breaker()将是null
            if (CloudClient.breaker() != null) {
                // 限流
                CloudClient.breaker().entry("root");
            }
            chain.doFilter(ctx);
        } catch (BreakerException ex) {
            // 限流
            ApiCode apiCode = ApiCodes.CODE_400("请求太频繁了");
            ctx.render(Result.failure(apiCode.getCode(), apiCode.getMessage()));
        } catch (AuthException e) {
            // 鉴权异常
            AuthStatus status = e.getStatus();
            ctx.render(Result.failure(status.code, status.message));
        } catch (Exception ex) {
            // 其它异常
            ApiCode apiCode = ApiCodes.CODE_400(ex);
            ctx.render(Result.failure(apiCode.getCode(), apiCode.getMessage()));
        }
        long times = System.currentTimeMillis() - start;
        log.info("请求【{}】完成，耗时:【{}ms】", ctx.path(), times);
    }

}
